function CRP = insertCommon(Q, insert2, F)

%Common function to insert items to S3DB using S3QL given the following:
%Q should be a struct that contains the following
%   Q.key :key to access the deployment
%   Q.url :url to eh deployment
%insert2 is a string indicating what type of insert this going to be. For
%example insert2 could be project, collection, item etc. Please look at
%S3DB documentation to find all valid insert2 values
%F is a struct containing the all allowed for the respective insert2
%variable. For example if insert2 is an 'statement' then F can be 
%constructed as following:
%   F.item_id
%   F.rule_id
%   F.value
%The fieldnames should match S3QL accepted names. The function will return
%error codes returned from S3DB

%R0mesh Stanislaus May 2009 //summer of change//

%check to see if SS is a struct
if not(isstruct(F))
    error('The third arg should be a struct...see help')
end

%get filednames
fNames = fieldnames(F);

%generate query body
body='';
for i = 1:size(fNames,1)
    try
        body = [body,'<',fNames(i),'>',num2str(getfield(F,fNames{i})),'</',fNames(i),'>'];
    catch
        body = [body,'<',fNames(i),'>',getfield(F,fNames{i}),'</',fNames(i),'>'];
    end
end

%combine the cell contents together
body=[body{1,:}];

%construct S3QL query
front = ['<S3QL><insert>',lower(insert2),'</insert><where>'];
back = '</where></S3QL>';

S1 = [front,body,back];

Q.X = S1;

try
    [D1,Q]=s3db_read(Q); % -2
catch
    error('Please check your syntax to s3ql and try again...')
end

if str2num(D1.error_code)
    error(D1)
end

CRP = D1;
